package com.mmloo.manage.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mmloo.common.model.BaseModel;
import com.mmloo.common.page.Pager;
import com.mmloo.common.repository.CURDRepository;
import com.mmloo.common.util.DataTable;
import com.mmloo.common.util.GenericsUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.*;

/**
 * Created by jessy on 2015/10/8.
 * 促销商品管理
 */
@Service
public class PromotionService<T extends BaseModel> {
    protected transient Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    CURDRepository curdRepository;

    private Class<T> persistentClass;

    protected Class<T> getCurClass() {
        if (persistentClass == null) {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
                    .getGenericSuperclass()).getActualTypeArguments()[0];
        }
        return persistentClass;
    }


    public String  generateId(String tableName) throws Exception {
        ArrayList<byte[]> arrayList = new ArrayList<byte[]>();
        arrayList.add(tableName.getBytes());
        curdRepository.incr(arrayList);
        return curdRepository.get(arrayList);
    }

    public void add(T entity) throws Exception {
        ArrayList<byte[]> hsetparames = new ArrayList<>();
        String type = entity.getClass().getSimpleName();
        switch (type){
            case "GroupBuy":
                hsetparames.add(DataTable.GROUP_BUYING_DETAIL_DATA.getBytes());
                hsetparames.add(generateId(DataTable.GROUP_BUYING_ID_SQUENCE).getBytes());
                entity.setId(generateId(DataTable.GROUP_BUYING_ID_SQUENCE));
                break;
            case "GivingBuy":
                hsetparames.add(DataTable.GIVING_BUYING_DETAIL_DATA.getBytes());
                hsetparames.add(generateId(DataTable.GIVING_BUYING_ID_SQUENCE).getBytes());
                entity.setId(generateId(DataTable.GIVING_BUYING_ID_SQUENCE));
                break;
            case "FastBuy":
                hsetparames.add(DataTable.FAST_BUYING_DETAIL_DATA.getBytes());
                hsetparames.add(generateId(DataTable.FAST_BUYING_ID_SQUENCE).getBytes());
                entity.setId(generateId(DataTable.FAST_BUYING_ID_SQUENCE));
                break;
            case "CombinationBuy":
                hsetparames.add(DataTable.COMBINATION_BUYING_DETAIL_DATA.getBytes());
                hsetparames.add(generateId(DataTable.COMBINATION_BUYING_ID_SQUENCE).getBytes());
                entity.setId(generateId(DataTable.COMBINATION_BUYING_ID_SQUENCE));
                break;
        }
        hsetparames.add(entity.toJson().getBytes());
        curdRepository.hset(hsetparames);
    }

    public List<T> findAll(String keyword,Class clazz) throws Exception {

        String type = clazz.getSimpleName();
        Map<String, String> data = new HashMap<>();
        switch (type) {
            case "GroupBuy":
                data = curdRepository.hscanAll(DataTable.GROUP_BUYING_DETAIL_DATA);
                break;
            case "GivingBuy":
                data = curdRepository.hscanAll(DataTable.GIVING_BUYING_DETAIL_DATA);
                break;
            case "FastBuy":
                data = curdRepository.hscanAll(DataTable.FAST_BUYING_DETAIL_DATA);
                break;
            case "CombinationBuy":
                data = curdRepository.hscanAll(DataTable.COMBINATION_BUYING_DETAIL_DATA);
                break;
        }

        Set<Map.Entry<String, String>> entrySet = data.entrySet();
        List<T> list = new ArrayList<>();
        if (!entrySet.isEmpty())
            for (Map.Entry<String, String> anEntrySet : entrySet) {
                String value = anEntrySet.getValue();
                //关键字判断
                //todo to check it
                if(!StringUtils.isEmpty(keyword)) {
                    if(!value.contains(keyword))
                        break;
                }
                T parseObject = (T) JSONObject.parseObject(value, clazz);

                //有效对象
                if (parseObject.getValid() == 1)
                    list.add(parseObject);
            }

        return list;
    }

    public Pager<T> getByPager(Pager<T> pager,String keyword,Class clazz) throws Exception {
        try {

            List<T> goodses = findAll(keyword,clazz);
            pager.setList(goodses);
            pager.setCount(goodses.size());
            return pager;
        }catch (Exception e){
            throw new DocumentException("获取数据失败");
        }

    }
    public T find(String id) throws Exception {
        ArrayList<byte[]> parames = new ArrayList<>();
        String type = getCurClass().getSimpleName();
        switch (type) {
            case "GroupBuy":
                parames.add(DataTable.GROUP_BUYING_DETAIL_DATA.getBytes());
                break;
            case "GivingBuy":
                parames.add(DataTable.GIVING_BUYING_DETAIL_DATA.getBytes());
                break;
            case "FastBuy":
                parames.add(DataTable.FAST_BUYING_DETAIL_DATA.getBytes());
                break;
            case "CombinationBuy":
                parames.add(DataTable.COMBINATION_BUYING_DETAIL_DATA.getBytes());
                break;
        }
        parames.add(id.getBytes());
        String result = curdRepository.hget(parames);
        return JSON.parseObject(result, getCurClass());
    }

    public void update(T entity) throws Exception {
        ArrayList<byte[]> parames = new ArrayList<>();
        String type = entity.getClass().getSimpleName();
        switch (type) {
            case "GroupBuy":
                parames.add(DataTable.GROUP_BUYING_DETAIL_DATA.getBytes());
                break;
            case "GivingBuy":
                parames.add(DataTable.GIVING_BUYING_DETAIL_DATA.getBytes());
                break;
            case "FastBuy":
                parames.add(DataTable.FAST_BUYING_DETAIL_DATA.getBytes());
                break;
            case "CombinationBuy":
                parames.add(DataTable.COMBINATION_BUYING_DETAIL_DATA.getBytes());
                break;
        }
        parames.add(entity.getId().getBytes());
        parames.add(entity.toJson().getBytes());
        curdRepository.hset(parames);
    }

    public void delete(String id) throws Exception {
        T entity = find(id);
        entity.setValid(0);
        update(entity);
    }



}
